var PeerConnection = (window.PeerConnection ||
    window.webkitPeerConnection ||
    window.webkitRTCPeerConnection ||
    window.mozRTCPeerConnection);
var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
var localVideo = null, remoteVideo = null, localVideoStream = null,
    videoCallButton = null, endCallButton = null,
    pc = null, socket = null, dc = null, dc1 = null, msgBlock = null;

var RTCSDP = window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
var ice = {
    "iceServer": [
        { "url": "stun:stun.l.google.com:19302" },
        { 'url': 'stun:stun.services.mozilla.com' }
    ]

};
var fileSendBtn = null, fileSend = null;
var inputmsg;
socket = new WebSocket("wss:" + window.location.href.substring(window.location.protocol.length).split('#')[0]);
function pageReady() {
    if (getUserMedia) {
        inputmsg = document.getElementById('msgIpt');
        videoCallButton = document.getElementById("videoCallButton");
        endCallButton = document.getElementById('endCallButton');
        localVideo = document.getElementById('localVideo');
        remoteVideo = document.getElementById('remoteVideo');
        dataSend = document.getElementById('sendData');
        msgBlock = document.getElementById('msgs');
        fileSend = document.getElementById('fileIpt');
        fileSendBtn = document.getElementById('sendFileBtn');
        fileSendBtn.addEventListener('click', fileClick);
        dataSend.addEventListener('click', textsend);
        videoCallButton.removeAttribute('disabled');
        $("#msgtext").bind('DOMNodeInserted', function (e) {
            alert('element now contains: ' + $(e.target).html());
        });
        videoCallButton.addEventListener('click', initiateCall);
        endCallButton.addEventListener('click', function (evt) {
            endCall();
            socket.send(JSON.stringify({ "closeConnection": true }));
        });
    } else {
        alert("Sorry, your brower does not support Webrtc");
    }
}

function initiateCall() {
    prepareCall();
    getUserMedia.call(navigator, { 'audio': true, 'video': true }, function (stream) {
        localVideoStream = stream;
        localVideo.src = URL.createObjectURL(localVideoStream);
        pc.addStream(localVideoStream);
        createAndSendOffer();
    }, function (error) {
        console.log('getUserMedia err :' + err)
    })

};

function handleChannel(chan) {
    chan.onerror = function (err) { console.log("dataChannel error :" + error) }
    chan.onclose = function () { console.log("dataChannel close!!!") }
    chan.onopen = function (evt) {
        console.log("hello world")
        chan.send("dataChannel connection established . Hello peer")
    }
    chan.onmessage = function (msg) {
        console.log(msg);
        if (msg.data instanceof Blob) {
            processBlob(msg.data);
            console.log("data is :" + msg.data);
        } else {
            processText(msg.data);
            console.log("data is :" + msg.data);
        }
    }
}

socket.onmessage = function (evt) {
    var signal = null;

    if (!pc) { console.log("i need " + pc); answerCall(); }

    signal = JSON.parse(evt.data);
    if (signal.sdp) {
        console.log("Received SDP from remote peer.");
        pc.setRemoteDescription(new RTCSDP(signal.sdp));
    } else if (signal.candidate) {
        console.log("Received ICECandidate from remote peer.");
        pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
    } else if (signal.closeConnection) {
        console.log("Received 'close call' signal from remote peer.");
        endCall();
    }
};


// Ready connecting
function prepareCall() {
    console.log(pc)
    pc = new PeerConnection(ice);
    pc.onicecandidate = onIceCandidateHandler;

    pc.onaddstream = onAddStreamHandler;
    try {
        // Reliable Data Channels not yet supported in Chrome
        // Data Channel api supported from Chrome M25.
        // You need to start chrome with  --enable-data-channels flag.
        dc = pc.createDataChannel("mydata");
        //     {reliable: true});
    } catch (e) {
        console.log("data err: " + e.message);
    }
    pc.ondatachannel = function (ev) {
        console.log('Data channel is created!');
        var chan = ev.channel;
        chan.onerror = function (err) { console.log("dataChannel error :" + error) }
        chan.onclose = function () { console.log("dataChannel close!!!") }
        chan.onopen = function (evt) {
            console.log("hello world")
            chan.send("dataChannel connection established . Hello peer")
        }
        chan.onmessage = function (msg) {
            // console.log("message:" + msg.data);
            var datajson = JSON.parse(msg.data);
            console.log(datajson)
            if (datajson['type'] == 'file') {
                var link = document.createElement('a');
                link.href = datajson['download'];
                link.download = datajson['name'];
                link.click();
                addRece('recive a file');
            } else {
                addRece(datajson['data']);
            }
        }
    };
    console.log(pc)
}

/.--------------dataSend-----------------./
function addRece(s) {
    msgBlock.innerHTML += ('<div class="other_msg"><div class="chat_msg">' +
        '<a class="head" href="www.baidu.com" target="_blank"><img src="img/head.jpg"></a>' +
        '<i class="msgarrow" style="top: 16px;"></i>' +
        '<div class="msgtext" style="margin-top: 6px;">' + s + '</div></div></div>')
}
function addText(s) {
    // var div = document.createElement('div');
    // var text = document.createElement('div');
    // var i = document.createElement('i');
    // div.className = "chat_msg";
    // i.className = 'msgarrow';
    // text.id = 'msgtext';
    // text.className = 'msgtext';
    // text.innerText = "me: " + s;
    // div.appendChild(i);
    // div.appendChild(text);
    // msgBlock.appendChild(div);
    msgBlock.innerHTML += ('<div class="my_msg"><div class="chat_msg">' +
        '<a class="head" href="www.baidu.com" target="_blank"><img src="img/head.jpg"></a>' +
        '<i class="msgarrow" style="top: 16px;"></i>' +
        '<div class="msgtext" style="margin-top: 6px;">' + s + '</div></div></div>')
}

function textsend() {
    var s = inputmsg.value;
    var packet = {
        type: 'text',
        data: s
    }
    dc.send(JSON.stringify(packet));
    addText(s);
}

function fileClick() {
    var file = fileSend.files[0];
    console.log(file);
    var packet = {
        type: 'file',
        name: file.name,
        download: ''
    }
    if (file) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onprogress = function (e) {
            console.log(e.loaded / file.size)
        }
        reader.onload = function (e) {
            packet['download'] = window.URL.createObjectURL(file);
            dc.send(JSON.stringify(packet));
            console.log(JSON.stringify(packet))
        };

    }
}

function endCall() {
    function obj() { }
    pc.close();
    localVideoStream.getTracks().forEach(function (track) {
        track.stop();
    })
    localVideo.src = '';
    remoteVideo.src = '';
    videoCallButton.removeAttribute('disabled');
    endCallButton.setAttribute('disabled', true);
    pc = null;
}

function onIceCandidateHandler(evt) {
    if (!evt || !evt.candidate) return;
    socket.send(JSON.stringify({ "candidate": evt.candidate }));
};

function onAddStreamHandler(evt) {
    videoCallButton.setAttribute('disabled', true);
    endCallButton.removeAttribute('disabled');
    remoteVideo.src = URL.createObjectURL(evt.stream);
}

function answerCall() {
    prepareCall();

    getUserMedia.call(navigator, { "audio": true, 'video': true }, function (stream) {
        localVideoStream = stream;
        localVideo.src = URL.createObjectURL(localVideoStream);
        pc.addStream(localVideoStream);
        createAndSendAnswer();
    }, function (error) {
        console.log("getUserMedia err :" + error);
    })
}

function createAndSendAnswer() {
    pc.createAnswer(
        function (answer) {
            var ans = new RTCSDP(answer);
            pc.setLocalDescription(ans, function () {
                socket.send(JSON.stringify({ 'sdp': ans }));
            },
                function (error) {
                    console.log("create answer error sdp:" + error);
                })
        }, function (error) {
            console.log("create answer err: " + error);
        }
    );
}

function createAndSendOffer() {
    pc.createOffer(
        function (offer) {
            var off = new RTCSDP(offer);
            pc.setLocalDescription(new RTCSDP(off),
                function () {
                    socket.send(JSON.stringify({ "sdp": off }));
                },
                function (error) {
                    console.log("create sdp err :" + error);
                });
        }, function (error) {
            console.log("create offer err: " + error);
        }
    );
};